package cn.tedu.controller;
/*前端与springMVC
  //通过MVC模式接收【数据入库】
 */
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@RestController
@CrossOrigin //跨域问题
@RequestMapping("car")
public class CarController {
    @RequestMapping("save")
    public Car save (Car c) throws Exception {
       //写了jdbc数据库驱动连接，就不用添加JDBC的依赖的，但要添加MySQL依赖包

        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql:///abc?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url, "root", "root");
        String sql = "insert into car values (?,?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setInt(1, c.getId());//拿到请求的数据并入库
        ps.setString(2, c.getName());
        ps.setString(3, c.getType());
        ps.setString(4, c.getColor());
        ps.setDouble(5,c.getPrice());

        ps.executeUpdate();
        System.out.println("数据保存成功！！");
        System.out.println(c);//后台打印

        //释放资源
        ps.close();
        conn.close();

        return c;//返回对象必须放在最后，否则报错，前端打印
    }
}
